package gui;

import java.sql.SQLException;
import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;

import tables.UserHistory;

import DBside.Tools.History;
import LogicSide.FollowersModifier;
import LogicSide.HistoryModifier;

public class Friends {

	private static String newFollowName = "";
	private static String selected_follow_name = "";
	private static Table feedTable;
	private static int selected_history_index = -1;
	private static java.util.List<UserHistory> history_list = null;

	public static Composite createFriends(final Shell shell) {
		//update 
		Main.inSearch = false;
		selected_history_index = -1;
		history_list = null;
		
		
		Composite friendsComposite = new Composite(shell, SWT.BORDER);
		friendsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		friendsComposite.setLayout(new GridLayout(1, false));

		/**
		 * Will contain two composite first will show followed users and will
		 * allow to add new users to follow the second will show the list of all
		 * their activities and will allow to "do the same"
		 */

		Composite followersComposite = new Composite(friendsComposite, SWT.NONE);
		followersComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				false, 1, 1));
		followersComposite.setLayout(new GridLayout(2, false));
		followersComposite.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_MAGENTA));

		// list showing all followed users
		final List followedList = new List(followersComposite, SWT.V_SCROLL
				| SWT.BORDER | SWT.MULTI);
		followedList.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
		Rectangle clientArea = shell.getClientArea();
		int list_width = (int) (clientArea.width / 5.0);
		int list_height = (int) (clientArea.height / 3.0);
		GridData listStyle = new GridData(list_width, list_height);
		listStyle.verticalAlignment = SWT.TOP;
		followedList.setLayoutData(listStyle);
		//

		// list click listener
		followedList.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				selected_follow_name = followedList.getItem(followedList
						.getSelectionIndex());
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						try {
							history_list = HistoryModifier.getUserHistory(selected_follow_name, Main.session);
							
							Main.display.asyncExec(new Runnable() {
								@Override
								public void run() {
									feedTable.clearAll();
									feedTable.setItemCount(0);
									for(UserHistory uh : history_list){
										TableItem item = new TableItem (feedTable, SWT.NONE);
										item.setText(uh.toString());
									}	
								}
							});
						} catch (SQLException e) {
							Main.display.asyncExec(new Runnable() {
								public void run() {
									Utils.popUpFailure(shell);
								}
							});
						} 
						
					}
				}).start();
			}
		});

		//

		// Get all followed friends and update list
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					final java.util.List<String> followedNameList = FollowersModifier
							.getAllFollowed(Main.session);
					Main.display.asyncExec(new Runnable() {

						@Override
						public void run() {
							if(!followedList.isDisposed()){
							for (String followedName : followedNameList) {
								followedList.add(followedName);
							}
							}
						}
					});
				} catch (SQLException e) {
					Utils.popUpFailure(shell);
				}

			}
		});
		thread.start();
		//

		// add/remove user to/from followed
		Composite controlComposite = new Composite(followersComposite, SWT.NONE);
		controlComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));
		controlComposite.setLayout(new GridLayout(4, false));

		Label usernameLabel = new Label(controlComposite, SWT.BORDER);
		usernameLabel.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true,
				1, 1));
		usernameLabel.setText("Username: ");
		usernameLabel.setBackground(Display.getCurrent().getSystemColor(
				SWT.COLOR_WHITE));

		final Text usernameText = new Text(controlComposite, SWT.SINGLE | SWT.BORDER);
		usernameText.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
		usernameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true,
				1, 1));

		Button addButton = new Button(controlComposite, SWT.PUSH | SWT.FLAT);
		addButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false, 1,
				1));
		addButton.setText("Follow");
		addButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				newFollowName = usernameText.getText();
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							final int result = FollowersModifier.addFollow(
									newFollowName, Main.session);
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									if (result != -1) {
										Utils.popUpBox("Success", "User added",
												shell);
										try {
											final java.util.List<String> followedNameList = FollowersModifier
													.getAllFollowed(Main.session);
											Main.display.asyncExec(new Runnable() {
												@Override
												public void run() {
													followedList.removeAll();
													for (String followedName : followedNameList) {
														followedList.add(followedName);
													}
													Utils.regularCursor(Main.display, shell);
												}
											});
										} catch (SQLException e) {
											Main.display.asyncExec(new Runnable() {
												@Override
												public void run() {
													Utils.popUpFailure(shell);
												}
											});
										}
									} else {
										Utils.popUpBox("Failure",
												"Couldn't add user", shell);
									}
								}
							});
						} catch (SQLException e) {
							Utils.popUpFailure(shell);
						}
					}
				});
				thread.start();
			}
		});

		Button deleteButton = new Button(controlComposite, SWT.PUSH | SWT.FLAT);
		deleteButton.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, true,
				1, 1));
		deleteButton.setText("Delete");

		deleteButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							if (selected_follow_name.length() > 0)
								FollowersModifier.removeFollow(
										selected_follow_name, Main.session);
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									if (selected_follow_name.length() == 0){
										Utils.popUpBox(
												"Error",
												"Please select a username to remove",
												shell);
									}
									else{
										Utils.popUpBox("Success",
												"Removed username", shell);
										try {
											final java.util.List<String> followedNameList = FollowersModifier
													.getAllFollowed(Main.session);
											Main.display.asyncExec(new Runnable() {
												@Override
												public void run() {
													followedList.removeAll();
													for (String followedName : followedNameList) {
														followedList.add(followedName);
													}
													Utils.regularCursor(Main.display, shell);
												}
											});
										} catch (SQLException e) {
											Main.display.asyncExec(new Runnable() {
												@Override
												public void run() {
													Utils.popUpFailure(shell);
												}
											});
										}
									}
								}
							});
						} catch (SQLException e) {
							Main.display.asyncExec(new Runnable() {

								@Override
								public void run() {
									Utils.popUpFailure(shell);
								}
							});
						}

					}
				});
				thread.start();
			}
		});
		//
		Button doTheSameButton = new Button(controlComposite, SWT.FLAT | SWT.PUSH);
		doTheSameButton.setLayoutData(new GridData(SWT.FILL, SWT.TOP, false, false,
				4, 4));
		doTheSameButton.setText("Do the same");
		doTheSameButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				if(selected_history_index != -1){
					Utils.loadingCursor(Main.display, shell);
					final UserHistory uh = history_list.get(selected_history_index) ;
					new Thread(new Runnable() {
						
						@Override
						public void run() {
							if(uh.getHistory().equals(History.LISTINTOSONG)){
								final java.util.List<String> playlistSongs = new ArrayList<String>();
								playlistSongs.add(uh.getEntity_name());
								Main.display.asyncExec(new Runnable() {

									@Override
									public void run() {
										// remove current displaying panel
										Main.current.dispose();
										// update current displaying panel
										Main.current = PlayNow.createPlayNow(shell,
												playlistSongs);
										// needed for it to work
										shell.layout(true, true);
										Utils.regularCursor(Main.display, shell);
									}
								});
							}
							else{
								try {
									HistoryModifier.doTheSame(uh, Main.session);
									
									try {
										final java.util.List<String> followedNameList = FollowersModifier
												.getAllFollowed(Main.session);
										Main.display.asyncExec(new Runnable() {
											@Override
											public void run() {
												followedList.removeAll();
												for (String followedName : followedNameList) {
													followedList.add(followedName);
												}
												Utils.regularCursor(Main.display, shell);
											}
										});
									} catch (SQLException e) {
										Utils.popUpFailure(shell);
									}
									
								} catch (SQLException e) {
									Main.display.asyncExec(new Runnable() {
										public void run() {
											Utils.popUpFailure(shell);
											Utils.regularCursor(Main.display, shell);
										}
									});
								}
							}
							
						}
					}).start();
				}
				else{
					Utils.popUpBox("Error", "Select a row!", shell);
				}
			}
		});

		//
		
		feedTable = new Table(friendsComposite, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
		feedTable.setLinesVisible (true);
		feedTable.setHeaderVisible (true);
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		data.heightHint = 200;
		feedTable.setLayoutData(data);
		feedTable.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_GRAY));
		
		String[] titles = new String[] {"History"};

		for (int i=0; i<titles.length; i++) {
			TableColumn column = new TableColumn (feedTable, SWT.NONE);
			column.setText (titles [i]);
		}	
		
		for (int i=0; i<titles.length; i++) {
			feedTable.getColumn (i).pack ();
		}
		//
		feedTable.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				selected_history_index = feedTable.getSelectionIndex();
			}
		});
		

		return friendsComposite;

	}
}
